# 托盘参考：
# https://blog.csdn.net/wukai_std/article/details/67639985
# https://blog.csdn.net/daiyinger/article/details/52700738
# 重写关闭事件参考：
# https://blog.csdn.net/u010139869/article/details/79483274
import configparser
import os
import sys
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from datetime import datetime

import qtawesome as qta
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QAction, QSystemTrayIcon, QMenu, QApplication
from apscheduler.schedulers.background import BackgroundScheduler
from qtpy import QtWidgets, QtCore


class Job(object):
    def __init__(self, hour, minute, execute_path):
        self.hour = hour
        self.minute = minute
        self.execute_path = execute_path


class Tray(QWidget):

    def __init__(self):
        super(self.__class__, self).__init__()
        self.job = self.loadJob()
        mainIcon = qta.icon('fa5s.dna',
                            active='fa5s.balance-scale',
                            color='black',
                            color_active='orange')
        self.setWindowIcon(mainIcon)
        self.setWindowTitle("任务调度")
        self.tray = QSystemTrayIcon(self)
        self.tray.setIcon(QIcon(mainIcon))
        self.tray.setToolTip("任务调度")
        restoreAction = QAction("&打开", self, triggered=self.showNormal)
        quitAction = QAction("&退出", self, triggered=QApplication.instance().quit)  # 退出APP

        self.trayMenu = QMenu(self)
        self.trayMenu.addAction(restoreAction)
        self.trayMenu.addSeparator()
        self.trayMenu.addAction(quitAction)
        self.tray.setContextMenu(self.trayMenu)
        self.tray.show()
        self.show()

    def setupUi(self):
        self.window().resize(500, 500)
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton_2 = QtWidgets.QPushButton(self)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton = QtWidgets.QPushButton(self)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.textEdit = QtWidgets.QTextEdit(self)
        self.textEdit.setObjectName("textEdit")
        self.horizontalLayout_2.addWidget(self.textEdit)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.pushButton_2.setText(_translate("Form", "重载"))
        self.pushButton.setText(_translate("Form", "隐藏"))
        self.pushButton_2.clicked.connect(self.reloadConfig)
        self.pushButton.clicked.connect(self.closeWindow)

    def closeWindow(self):
        self.window().close()

    def closeEvent(self, event):
        event.ignore()  # 忽略关闭事件
        self.hide()  # 隐藏窗体

    def loadJob(self):
        config = configparser.ConfigParser()
        config.read(os.path.abspath('TaskConfig.ini'))
        return Job(config.get("TASK", "HOUR"), config.get("TASK", "MINUTE"), config.get("TASK", "EXECUTE_PATH"))

    def startScheduler(self):
        self.textEdit.append("启动调度器")
        self.textEdit.append("加载配置.......")
        self.textEdit.append("时 : {0}".format(self.job.hour))
        self.textEdit.append("分 : {0}".format(self.job.minute))
        self.textEdit.append("路径 : {0}".format(self.job.execute_path))
        self.textEdit.append("装载 JOB .....")
        scheduler = BackgroundScheduler()
        scheduler.add_job(self.runBat, 'cron', hour=self.job.hour, minute=self.job.minute)
        try:
            scheduler.start()
            self.textEdit.append("启动成功")
        except (KeyboardInterrupt, SystemExit):
            pass

    def tick(self):
        self.textEdit.append('运行时间 : %s' % datetime.now())

    def runBat(self):
        self.tick()
        os.system(self.job.execute_path)
        self.textEdit.append('运行完成 : %s' % datetime.now())

    def reloadConfig(self):
        self.textEdit.setText("")
        self.textEdit.append("---------------- Start Reload Config --------------")
        self.job = self.loadJob()
        self.startScheduler()
        self.textEdit.append("---------------- Start Scheduler Success ---------------!")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Tray()
    win.setupUi()
    win.startScheduler()
    sys.exit(app.exec_())
